<?php
/**
 * Created by PhpStorm.
 * User: BlueIdeaLirui
 * Date: 2019/11/8
 * Time: 18:29
 */

namespace search\controllers\bigdata;

use business\base\services\SystemConfigService;
use business\company\services\queues\SupplierProducerService;
use business\company\services\SelectionSupplierService;
use business\elasticsearch\services\IntegrateSupplierService;
use business\mns\AlimnsService;
use common\queue\QueueConstants;

/**
 * 供应商搜索
 * Class SupplierController
 * @package search\controllers\bigdata
 */
class SupplierController extends BaseController
{
    public $enableCsrfValidation = false;

    /**
     * 平台/大数据供应商查询列表——此接口仅寻源（供应商搜索）调用
     * @return \business\base\models\ResultModel
     */
    public function actionIndex()
    {
        try {
            // ==================================================BEGIN
            // BEGIN—END圈起来的代码块，通过现有的供应商寻源接口的业务梳理，发现这些入参没有作用
            // 但不确定是否有别的业务场景有使用到此接口，所以暂时没有删除
            // 记录时间：2021-08-16
            $catWord = addslashes($this->getParam('catWord'));//分类关键词 多个用 @@## 隔开
            $companyWord = addslashes($this->getParam('companyWord'));//公司名称关键词 多个用 @@## 隔开
            $isBoutique = $this->getParam('isBoutique'); // 是否精选供应商
            $isDiamond = $this->getParam('isDiamond'); // 是否为砖石供应商
            $basicCategoryCode2 = $this->getParam('basicCategoryCode2'); // 新增服务二级分类筛选
            $serviceLocationCode = $this->getParam('serviceLocationCode');//服务区域,可选多个， - 隔开
            $orderBy = $this->getParam('orderBy');
            $customScore = (int)$this->getParam('customScore', 'get', 1);
            $customScore = $customScore > 0;
            // ==================================================END

            $keyword            = addslashes($this->getParam('keyword')); //关键词 多个用 @@## 隔开
            $area               = $this->getParam('area');
            $basicCategoryCode  = $this->getParam('basicCategoryCode'); //服务分类，可选多个， - 隔开
            $registerCapital    = $this->getParam('registerCapital');
            $registerCapitalEnd = $this->getParam('registerCapitalEnd');
            $supplierTags       = $this->getParam('supplierTags');
            $channel            = $this->getParam('channel');
            $page               = (int)$this->getParam('page', 'get', '1');
            $pageSize           = (int)$this->getParam('pagesize', 'get', '10');

            //后续增加的搜索项， 放入options参数
            $options = [];
            $options['basicCategoryCode'] = $basicCategoryCode;
            $options['isBoutique'] = $isBoutique == true ? true : '';
            $options['isDiamond'] = $isDiamond == true ? true : '';
            $options['basicCategoryCode2'] = $basicCategoryCode2;
            $options['serviceLocationCode'] = $serviceLocationCode;
            $options['catWord'] = $catWord;
            $options['companyWord'] = $companyWord;
            $boostModeConfig = SystemConfigService::get('boostMode',0);
            $options['boostMode'] = $this->getParam('boostMode', 'get', $boostModeConfig);
            $options['inStorageCount'] = $this->getParam('inStorageCount', 'get', 0); // 入库次数量
            $options['projectCount'] = $this->getParam('projectCount', 'get', 0); // 项目案例数量
            $options['linkNumber'] = $this->getParam('linkNumber', 'get', 0); // 联系人数量
            $options['searchScope'] = $this->getParam('searchScope', 'get', 0); // 搜索范围（0：不限； 1：公司名称； 2：经营产品； 3：合作开发商； 4：项目案例）
            $options['locationType'] = $this->getParam('locationType', 'get', 0);  // 所在地类型（0：公司所在地； 1：项目所在地）
            // 20230129新增
            $options['strategicCaseNum'] = $this->getParam('strategicCaseNum', 'get', 0); // 战略案例数量
            $options['turnoverNum'] = $this->getParam('turnoverNum', 'get', 0); // 营业额数量
            $options['listedType'] = $this->getParam('listedType', 'get', 0); // 上市类型
            // 判断来源，是否供应商搜索
            $options['channel'] = $channel;

            $integrateSupplierService = new IntegrateSupplierService();
            $list = $integrateSupplierService->getList($keyword, $area, $registerCapital, $registerCapitalEnd, $supplierTags, $page, $pageSize, $orderBy, $options,$customScore);
            $list['recommendList'] = [];
            /*
             * 获取推荐列表
             * 满足推荐条件：①调用此接口的业务方是供应商搜索（channel=search）；②搜索范围为不限；③检索词全词命中供应商名称；
             * 推荐逻辑：取检索词全词命中的供应商的前3个服务分类去ES抓取推荐列表
             * */
            if ($channel == 'search' && $options['searchScope'] == 0 && $keyword && isset($list['resultSet'][0]['companyName']) && $list['resultSet'][0]['companyName'] == $keyword) {
                $options = [
                    'basicCategoryCode' => implode(",", array_slice($list['resultSet'][0]['basicCategoryCode'], 0, 3)),
                    'notContain' => $keyword,
                ];
                $recommendList = $integrateSupplierService->getList("", "", "", "", "", 1, $pageSize, "", $options);
                $list['recommendList'] = $recommendList['resultSet'];
                $list['resultSet'] = [$list['resultSet'][0]];
                $list['resultNum'] = 1;
            }

            // 寻源触发，写入队列
            $queue = \yii::$app->iQueue->createClient(QueueConstants::DATA_GOVERNANCE_MAIN_SCENE);
            foreach ($list['resultSet'] as $v){
                if (isset($v['companyStatus']) && ($v['companyStatus'] == 2 || $v['companyStatus'] == 3)){
                    continue;
                }
                $params = [
                    'supplier_id' => $v['supplierId'],
                    'scene' => 'search',
                ];
                $queue->sendMsg(json_encode($params));
            }
            return $this->success($list);
        } catch (\Exception $ex){
            \Yii::error($ex->getMessage());
            return $this->error('', '获取失败，请稍后重试');
        }
    }

    /*
     * 获取供应商列表信息
     * */
    public function actionList()
    {
        $integrateSupplierService = new IntegrateSupplierService();
        $list = $integrateSupplierService->list();
        return $this->success($list);
    }

    /**
     * ES评分详细列表
     * @return \business\base\models\ResultModel
     */
    public function actionExplain()
    {
        try {
            $keyword            = addslashes(trim($this->getParam('keyword'))); //关键词 多个用 @@## 隔开
            $catWord            = addslashes($this->getParam('catWord'));//分类关键词 多个用 @@## 隔开
            $companyWord            = addslashes($this->getParam('companyWord'));//公司名称关键词 多个用 @@## 隔开
            $basicCategoryCode  = $this->getParam('basicCategoryCode'); //服务分类，可选多个， - 隔开
            $serviceLocationCode  = $this->getParam('serviceLocationCode');//服务区域,可选多个， - 隔开
            $explain = (int)$this->getParam('explain','get',0);

            $page               = (int)$this->getParam('page', 'get', '1');
            $pageSize           = (int)$this->getParam('pagesize', 'get', '10');

            //后续增加的搜索项， 放入options参数
            $options = [];
            $options['basicCategoryCode'] = $basicCategoryCode;
            $options['serviceLocationCode'] = $serviceLocationCode;
            $options['catWord'] = $catWord;
            $options['companyWord'] = $companyWord;
            $options['boostMode'] = $this->getParam('boostMode', 'get', 0);
            $options['scoreMode'] = $this->getParam('scoreMode', 'get', 0);
            return $this->success((new IntegrateSupplierService())->scoreExplain($keyword, $page, $pageSize, $options, $explain));
        } catch (\Exception $ex){
            \Yii::error($ex->getMessage());
            return $this->error('', '获取失败，请稍后重试');
        }
    }

    /**
     * 返回供应商标签
     * @return \business\base\models\ResultModel
     */
    public function actionGetTags()
    {
        try {
            $companyNames = $this->getParam('companyName');
            return $this->success((new IntegrateSupplierService())->getTags($companyNames));
        } catch (\Exception $ex){
            \Yii::error($ex->getMessage());
            return $this->error('', '获取失败，请稍后重试');
        }
    }

    /**
     * 通过公司名称查询供应商列表
     * @return \business\base\models\ResultModel
     */
    public function actionListByCompanyNames()
    {
        try {
            $companyNames = $this->getParam('companyNames', 'post');
            $page         = (int)$this->getParam('page', 'get', '1');
            $pageSize     = (int)$this->getParam('pagesize', 'get', '10');
            return $this->success((new IntegrateSupplierService())->getListByCompanyNames($companyNames, $page, $pageSize));
        } catch (\Exception $ex){
            \Yii::error($ex->getMessage());
            return $this->error('', '获取失败，请稍后重试');
        }
    }

    /**
     * @uses 通过供应商公司id查询供应商列表
     */
    public function actionListBySupplierIds()
    {
        try {
            $supplierIds = $this->getParam('supplierIds', 'get');
            $svr = new IntegrateSupplierService();
            $params = explode(",", $supplierIds);
            if (empty($params)){
                return $this->success([]);
            }
            $data = $svr->getListBySupplierIds($params);
            return $this->success($data);
        } catch (\Exception $ex) {
            \Yii::error("message:" . $ex->getMessage()." trance:".$ex->getTraceAsString()) ;
            return $this->error('', '获取失败，请稍后重试');
        }
    }

    public function actionStorageBySupplierIds()
    {
        try {
            $supplierIds = $this->getParam('supplierIds', 'get');
            $developerId = $this->getParam('developer_id', 'get');
            $supplierIds = explode(",", $supplierIds);
            if (empty($supplierIds)){
                return $this->success([]);
            }
            $data = (new SelectionSupplierService())->getMySupplierCount($supplierIds, $developerId);
            return $this->success($data);
        } catch (\Exception $ex) {
            \Yii::error("message:" . $ex->getMessage()." trance:".$ex->getTraceAsString()) ;
            return $this->error('', '获取失败，请稍后重试');
        }
    }

    /**
     * 触发单一供应商索引更新
     * @return \business\base\models\ResultModel
     */
    public function actionTriggerUpdate()
    {
        try {
            $supplierId = $this->getParam('supplierId');
            return $this->success((new SupplierProducerService())->single($supplierId));
        } catch (\Exception $ex){
            \Yii::error($ex->getMessage());
            return $this->error('', '操作失败，请稍后重试');
        }
    }

    /**
     * 获取供应商搜索，公司名称提示列表
     * @return \business\base\models\ResultModel
     */
    public function actionSuggestions()
    {
        try {
            $keyword = $this->getParam('keyword');
            $size = $this->getParam('size');
            return $this->success((new IntegrateSupplierService())->supplierSuggestions($keyword, $size));
        } catch (\Exception $ex){
            \Yii::error($ex->getMessage());
            return $this->error('', '获取失败，请稍后重试');
        }
    }

    /**
     * 通过公司名称列表判断公司是在平台存在
     * @return \business\base\models\ResultModel
     */
    public function actionIsExists()
    {
        try {
            $companyNames = \Yii::$app->request->post('company_names', 'post');
            if (empty($companyNames)) {
                return $this->success([]);
            }
            return $this->success((new IntegrateSupplierService())->supplierIsExists($companyNames));
        } catch (\Exception $ex){
            \Yii::error($ex->getMessage());
            return $this->error('', '获取失败，请稍后重试');
        }
    }
}
